<?php
namespace App\Common\Service;

use App\Exception\AppException;
use Hyperf\Contract\ConfigInterface;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Guzzle\ClientFactory;
use Psr\SimpleCache\CacheInterface;

class SmsService {

    /**
     * @Inject()
     * @var CacheInterface $cache
     */
    private $cache;

    /**
     * @Inject()
     * @var ConfigInterface $config
     */
    private $config;

    /**
     * @Inject()
     * @var ClientFactory $httpClient
     */
    private $httpClient;

    const URL = "https://api.mysubmail.com/message/send.json";

    private $prefix = "mobile:";

    public function send($mobile){
        if($this->cache->has($this->prefix . $mobile)){
            throw new AppException("短信发送太频繁,请稍后再试");
        }

        if($this->config->get("app_env") == "dev"){
            $code = "1234";
        }else{
            $code = random_int(1000,9999);
            $content = "【慢慢绘儿童之家】您的验证为:". $code ."，有效期为5分钟。";
            $response = $this->httpClient->create()->post(self::URL,[
                'json'=>[
                    'appid'=>$this->config->get("sms.appid"),
                    'signature'=>$this->config->get("sms.key"),
                    'to'=>$mobile,
                    'content'=>$content
                ]
            ]);

            if(!$response->getStatusCode() == 200){
                throw new AppException("短信发送失败:" . $response->getBody()->getContents());
            }
        }

        return $this->cache->set($this->prefix . $mobile,$code,300);
    }

    public function verify($mobile,$code){
        return $this->cache->get($this->prefix . $mobile) == $code;
    }
}